﻿#include	"Engine.Network.hpp"
#include	"Engine.String.hpp"

#include	<cstring>

namespace Engine { namespace Network {

	union IpConvert{
		uint32_t	uIp;
		char		sIp[4];
	};

	uint32_t GetIpInt(std::string & szIp) {
		union IpConvert iConvert;
		int pPart[4], nCount;

	#if defined(_WIN32)
		nCount = sscanf_s(szIp.c_str(), "%d.%d.%d.%d", &pPart[0], &pPart[1], &pPart[2], &pPart[3]);
	#else
		nCount = sscanf(szIp.c_str(), "%d.%d.%d.%d", &pPart[0], &pPart[1], &pPart[2], &pPart[3]);
	#endif

		if (nCount != 4)
			return 0;
		else {
			for (int n = 0; n < 4; ++n) iConvert.sIp[n] = pPart[n] & 0xFF;
			return iConvert.uIp;
		}
	}

	std::string GetIpString(uint32_t uRemoteIp) {
		union IpConvert iConvert;
		iConvert.uIp = uRemoteIp;
		int nPart1 = iConvert.sIp[0], nPart2 = iConvert.sIp[1], nPart3 = iConvert.sIp[2], nPart4 = iConvert.sIp[3];
		return String::Format("%d.%d.%d.%d", nPart1, nPart2, nPart3, nPart4);
	}

}}
